package com.gxc.integer;

import com.gxc.print.ArrayPrint;

/**
 * 59. 螺旋矩阵 II

 * 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
 */
public class GenerateMatrix {

    public static void main(String[] args) {
        ArrayPrint.print(handle(3));
    }

    public static int[][] handle(int n) {
        int[][] res = new int[n][n];

        int[][] direction = new int[][]{{0,1},{1,0},{0,-1},{-1,0}};
        int l = n * n;
        int row = 0;
        int col = 0;
        int dir = 0;
        int[] ints = direction[0];;
        for (int i = 1; i <= l; i++) {
            res[row][col] = i;
            //转向
            if ((row==0&&col==n-1) || (row==n-1 && col==n-1) || (row==n-1 && col==0)
                ||res[row + ints[0]][col + ints[1]] > 0) {
                dir = (dir+1) %4;
            }
            ints = direction[dir];
            row += ints[0];
            col += ints[1];
        }
        return res;
    }
}
